package net.gyapp.markim.module.mine.account;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.easyder.wrapper.base.view.WrapperSwipeActivity;
import com.easyder.wrapper.core.model.BaseVo;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.xuhao.android.libsocket.sdk.connection.interfacies.ISocketActionListener;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.WrapperApplication;
import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.module.basic.Helper;
import net.gyapp.markim.module.basic.MainActivity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.basic.event.ResponseChanged;
import net.gyapp.markim.module.basic.event.ResponseIml;
import net.gyapp.markim.module.mine.vo.LoginVo;
import net.gyapp.markim.module.mine.vo.MemberVo;
import net.gyapp.markim.utils.DeviceUtils;
import net.gyapp.markim.utils.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/7/6
 * Version: 1.0
 * Desc:
 */


public class LoginActivity extends WrapperSwipeActivity<CommonPresenter> {
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_cipher)
    EditText etCipher;

    String account, cipher;
    String preAccount; //上次登陆的账号

    private ISocketActionListener listener;

    public static Intent getIntent(Context context) {
        return getIntent(context, false);
    }

    public static Intent getIntent(Context context, boolean retry) {
        return getIntent(context, retry, true);
    }

    public static Intent getIntent(Context context, boolean retry, boolean enableSwipe) {
        return new Intent(context, LoginActivity.class).putExtra("retry", retry).putExtra("enableSwipe", enableSwipe).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_login;
    }


    @Override
    protected void initView(Bundle savedInstanceState, final TitleView titleView, Intent intent) {
        titleView.setCenterText("登录");
        setSwipeBackEnable(intent.getBooleanExtra("enableSwipe", true));
        preAccount = Helper.getAccount();
        etAccount.setText(preAccount);
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        ImManager.getInstance().connect();
//        listener = ImManager.getInstance().registerReceiver(new SocketActionAdapter() {
//            @Override
//            public void onSocketReadResponse(Context context, ConnectionInfo info, String action, ImPacket packet) {
//                super.onSocketReadResponse(context, info, action, packet);
//                if (packet.getCommand() == Command.COMMAND_LOGIN_RESP) {
//                    LogUtils.i("-- Socket -- ", "Login Success");
//                    ImResponse response = PacketHelper.parsePacket(packet);
//                    if (response instanceof LoginResponse) {
//                        onResult((LoginResponse) response);
//                    }
//                }
//            }
//        });
    }

//    private void onResult(final LoginResponse response) {
//        TaskScheduler.execute(new Task<Void>() {
//            @Override
//            public Void doInBackground() throws InterruptedException {
//                ImHelper.updateOrInsertUser(memberVo, response);
//                return null;
//            }
//
//            @Override
//            public void onSuccess(Void result) {
//
//            }
//        });
//    }


    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_LOGIN)) {
            processData((LoginVo) dataVo);
        } else if (url.contains(ApiConfig.API_INFO)) {
            processMemberData((MemberVo) dataVo);
        }else if(url.contains(ApiConfig.API_VISITOR_LOGIN)) {
            processData((LoginVo) dataVo);
        }
    }

    @Override
    protected void onDestroy() {
        ImManager.getInstance().unRegisterReceiver(listener);
        super.onDestroy();
    }

    @OnClick({R.id.tv_find_cipher, R.id.tv_register, R.id.btn_login, R.id.iv_login_qq, R.id.iv_login_wechat, R.id.iv_login_visitor})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_find_cipher:
                startActivity(CipherResetActivity.getIntent(mActivity));
                break;
            case R.id.tv_register:
                startActivity(RegisterActivity.getIntent(mActivity));
                break;
            case R.id.btn_login:
                account = etAccount.getText().toString();
                if (TextUtils.isEmpty(account)) {
                    showToast("请输入账号");
                    return;
                }

                cipher = etCipher.getText().toString();
                if (TextUtils.isEmpty(cipher)) {
                    showToast("请输入密码");
                    return;
                }

                login(account, cipher);
                break;
            case R.id.iv_login_qq:
                new BindDialog(mActivity).show();
                break;
            case R.id.iv_login_wechat:
                new BindDialog(mActivity).show();
                break;
            case R.id.iv_login_visitor:
//                new TipsDialog(mActivity).show();
                visitorLogin();
                break;
        }
    }

    @Subscribe
    public void accountChanged(AccountChanged changed) {
        if (changed.sign == AccountIml.ACCOUNT_REQISTER) {
            account = Helper.getAccount();
            etAccount.setText(account);
            etCipher.setText("");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void responseChanged(ResponseChanged changed) {
        if (changed.sign == ResponseIml.SIGN_PROCESS_LOGIN_RESPONSE_SUCCESS) {

        }
    }

    private void onSuccess() {
        onStopLoading();
        setAlias(account);
        Helper.setAccount(account);
        Helper.setCipher(cipher);
        EventBus.getDefault().post(new AccountChanged(AccountIml.ACCOUNT_LOGIN));
        enterHome();
    }

    private void login(String account, String cipher) {
        presenter.postData(ApiConfig.API_LOGIN, new RequestParams().put("userName", account).put("password", cipher).put("deviceToken", DeviceUtils.getDeviceId()).get(), LoginVo.class);
    }

    private void visitorLogin() {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_VISITOR_LOGIN, new RequestParams().put("deviceToken", DeviceUtils.getDeviceId()).get(), LoginVo.class);
    }

    private void processData(LoginVo dataVo) {
        HttpHeaders headers = OkGo.getInstance().getCommonHeaders();
        if (headers != null) {
            headers.clear();
        } else {
            headers = new HttpHeaders();
        }
        headers.put("Authorization", dataVo.token);
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        OkGo.getInstance().addCommonHeaders(headers);
        Helper.setToken(dataVo.token);
        account = dataVo.userName;
        cipher = dataVo.passWord;
        getMember();
    }

    private void getMember() {
        presenter.postData(ApiConfig.API_INFO, MemberVo.class);
    }

    private void processMemberData(MemberVo dataVo) {
        presenter.setForceShowDialog(true);
        WrapperApplication.setMember(dataVo);
        loginIm(account, cipher);
        onSuccess(); //默认直接成功
    }

    private void loginIm(String account, String cipher) {
        showLoadingView();
        ImManager.getInstance().login(account, cipher);
    }

    private void enterHome() {
        if (getIntent() != null && !getIntent().getBooleanExtra("retry", false)) {
            startActivity(MainActivity.getIntent(mActivity));
        } else {
            if (preAccount == null || !preAccount.equals(account)) {
                startActivity(MainActivity.getIntent(mActivity));
            }
        }
        finish();
    }

    private void setAlias(String account) {
        JPushInterface.setAlias(this, 0, account);
    }
}
